﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using MySql.Data;
using MySql.Data.MySqlClient;
using System.Data;
using System.Diagnostics;

namespace WordList
{
    class UserService
    {
        public static MySqlConnection GetConnection()
        {
            MySqlConnection connection;
            try { 
             connection = new MySqlConnection(
                "datasource=localhost;username=root;" +
                "password=rootpwd;database=word;charset=utf8");
            connection.Open();
            }
            catch (Exception err)//LiHaoyang's mysql env
            {
                Debug.WriteLine(err.Message);
                connection = new MySqlConnection(
                "datasource=localhost;username=root;" +
                "password=root;database=dictionary;charset=utf8");
                connection.Open();
            }
            return connection;
        }
        public static void CreateWordList(VocUser user)
        {
            using(MySqlConnection conn = GetConnection())
            {
                string sql = "select * from CET6";
                using (MySqlCommand command = new MySqlCommand(sql, conn))
                {
                    using (MySqlDataReader reader = command.ExecuteReader())
                    {
                        WordList wordList = new WordList();
                        List<Word> words = new List<Word>();
                        while (reader.Read())
                        {
                            if (reader.HasRows)
                            {
                                words.Add(new Word(reader.GetInt32(0), reader.GetString(1),
                                    reader.GetInt32(2), reader.GetInt32(3)));
                            }
                        }
                        wordList.List = words;
                        user.List.Add(wordList);
                    }
                }
            }
        }
        public static List<Word> GetWordList(VocUser user,int notebookNum=1)
        {
            if (notebookNum <= 0 || notebookNum > user.List.Count)
            {
                Debug.WriteLine("单词本序号不合法:");
                notebookNum = 1;
            }
            return user.List[notebookNum - 1].List;
        }
    }
}
